<template>
  <div class="expired-products-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>临期商品列表</h1>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>临期商品列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>



    <!-- 商品列表 -->
    <el-card class="products-card mt-4">
      <div v-if="loading" class="loading-container">
        <el-loading :fullscreen="false" text="加载中..."></el-loading>
      </div>

      <div v-if="errorMsg" class="error-message">
        <el-alert
            title="加载失败"
            :description="errorMsg"
            type="error"
            show-icon
        />
      </div>

      <div v-if="emptyState" class="empty-state">
        <el-empty description="暂无临期商品数据"></el-empty>
      </div>

      <el-table
          v-else
          :data="filteredProducts"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column
            type="index"
            label="序号"
            width="80"
        />
        <el-table-column
            label="商品图片"
            width="120"
        >
          <template #default="scope">
            <el-image
                :src="getImageUrl(scope.row.imgSrc)"
                :preview-src-list="[getImageUrl(scope.row.imgSrc)]"
                fit="cover"
                width="60"
                height="60">
              <!-- 加载失败时显示的占位图 -->
              <template #error>
                <div class="image-placeholder">
                  <el-icon><picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
            prop="name"
            label="商品名称"
            min-width="150"
        />
        <el-table-column
            prop="productId"
            label="产品号"
            width="120"
        />
        <el-table-column
            prop="stock"
            label="库存数量"
            width="120"
        >
          <template #default="scope">
            <span :class="getStockClass(scope.row.stock, scope.row.minStock, scope.row.maxStock)">
              {{ scope.row.stock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="updateTime"
            label="最后更新时间"
            width="180"
        />
        <el-table-column
            label="操作"
            width="120"
        >
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleViewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0 && !loading">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品详情弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="商品详情"
        :width="500"
    >
      <div class="product-detail">
        <el-row>
          <el-col :span="8">
            <el-image
                :src="getImageUrl(currentProduct.imgSrc)"
                :alt="currentProduct.name"
                fit="contain"
                class="detail-image"
            />
          </el-col>
          <el-col :span="16" class="detail-info">
            <el-descriptions column="1" border>
              <el-descriptions-item label="商品名称">{{ currentProduct.name }}</el-descriptions-item>
              <el-descriptions-item label="产品号">{{ currentProduct.productId }}</el-descriptions-item>
              <el-descriptions-item label="库存数量">{{ currentProduct.stock }}</el-descriptions-item>
              <el-descriptions-item label="最低库存">{{ currentProduct.minStock }}</el-descriptions-item>
              <el-descriptions-item label="最高库存">{{ currentProduct.maxStock }}</el-descriptions-item>
              <el-descriptions-item label="单价">{{ currentProduct.price }} 元</el-descriptions-item>
              <el-descriptions-item label="最后更新时间">{{ currentProduct.updateTime }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, toRefs, computed } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'DelayProduct',
  components: {
    Search,
    Refresh
  },
  data() {
    return {
      // 商品列表数据
      products: [],
      filteredProducts: [],
      total: 0,
      loading: false,
      errorMsg: '',
      emptyState: false,

      // 搜索和分页
      searchKeyword: '',
      currentPage: 1,
      pageSize: 10,

      // 详情弹窗
      dialogVisible: false,
      currentProduct: {}
    }
  },
  created() {
    // 页面加载时获取临期商品数据
    this.fetchExpiredProducts()
  },
  computed: {
    // 根据搜索关键词过滤商品
    filteredProducts() {
      if (!this.searchKeyword) {
        return this.products
      }
      const keyword = this.searchKeyword.toLowerCase()
      return this.products.filter(product =>
          product.name.toLowerCase().includes(keyword) ||
          product.productId.toString().includes(keyword)
      )
    }
  },
  methods: {
    // 获取临期商品数据
    async fetchExpiredProducts() {
      this.loading = true
      this.errorMsg = ''
      this.emptyState = false

      try {
        const response = await axios.get('http://localhost:8080/product/expired')

        // 假设后端返回格式为 { code: 200, msg: 'success', data: [...] }
        if (response.data.code === 200) {
          this.products = response.data.data
          this.total = response.data.data.length

          // 检查是否为空
          if (this.total === 0) {
            this.emptyState = true
          }
        } else {
          this.errorMsg = response.data.msg || '获取数据失败'
        }
      } catch (error) {
        console.error('获取临期商品失败:', error)
        this.errorMsg = '网络错误，无法获取数据'
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchKeyword = ''
      this.currentPage = 1
      this.fetchExpiredProducts()
    },

    // 处理分页大小变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
    },

    // 处理页码变化
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },

    // 查看商品详情
    handleViewDetail(product) {
      this.currentProduct = { ...product }
      this.dialogVisible = true
    },


    // 根据库存状态返回不同样式类
    getStockClass(stock, minStock, maxStock) {
      if (stock <= minStock) {
        return 'text-red-500 font-medium' // 低于最低库存，显示红色
      } else if (stock >= maxStock) {
        return 'text-blue-500' // 高于最高库存，显示蓝色
      } else {
        return 'text-green-500' // 正常库存，显示绿色
      }
    },
    // 处理图片路径，适配 Vite 环境
    getImageUrl(imgSrc) {
      // 如果没有图片路径，返回默认图片
      if (!imgSrc) {
        return new URL('../assets/default-product.png', import.meta.url).href;
      }

      // 检查是否已经是完整路径（如http开头）
      if (imgSrc.startsWith('http://') || imgSrc.startsWith('https://')) {
        return imgSrc;
      }

      // 处理assets中的图片
      try {
        // 假设图片存放在assets/images/products目录下
        return new URL(`../assets/${imgSrc}`, import.meta.url).href;
      } catch (error) {
        console.error(`图片${imgSrc}加载失败`, error);
        return new URL('../assets/default-product.png', import.meta.url).href;
      }
    },
  }

}
</script>

<style scoped>
.expired-products-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 20px;
  margin-bottom: 10px;
  color: #1f2329;
}

.search-card {
  background-color: #fff;
  padding: 15px 20px;
}

.products-card {
  background-color: #fff;
}

.loading-container {
  padding: 50px 0;
  text-align: center;
}

.error-message {
  padding: 20px;
}

.empty-state {
  padding: 50px 0;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.product-detail {
  padding: 10px 0;
}

.detail-image {
  width: 100%;
  height: 200px;
  border-radius: 4px;
}

.detail-info {
  padding-left: 20px;
}
/* 添加图片加载失败的样式 */
.image-placeholder {
  width: 60px;
  height: 60px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ccc;
}
</style>
